package com.ruoyi.system.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.config.AppConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.taskscheduler.TaskScheduler;
import com.ruoyi.system.domain.vo.MessageVO;
import com.ruoyi.system.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.Session;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class TaskSchedulerConfig {


    private RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

    private IMessageService messageService = SpringUtils.getBean(IMessageService.class);

    private PlatformTransactionManager transactionManager = SpringUtils.getBean(PlatformTransactionManager.class);


    @Bean
    public TaskScheduler taskScheduler() {
        log.info("TaskSchedulerConfig taskScheduler 初始化任务调度器");

        log.info("TaskSchedulerConfig taskScheduler 事务处理器：{}",transactionManager.getClass().getSimpleName());

        TaskScheduler taskScheduler = new TaskScheduler(AppConfig.taskSchedulerCorePoolSize);
        // 3. 添加固定延迟周期性任务
        taskScheduler.scheduleFixedDelayTask("cacheSyncDbTask", () -> {
            System.out.println("执行固定延迟任务 - 当前时间: " + 时间戳转化为日期(System.currentTimeMillis()));
            // 操作redis
            try {
                messageService.handleCacheSyncDb();
            }catch (Exception e){
                log.error("TaskSchedulerConfig handleCacheSyncDb 错误：{}",e.getMessage());
            }
        }, 1, AppConfig.cacheSyncDbIntervalTime, TimeUnit.SECONDS);

        return taskScheduler;
    }

    private static String 时间戳转化为日期(long  timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String formattedTime = sdf.format(date);
        return formattedTime;
    }

}
